package com.example.blank700.handlermessageprogess;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class HandlerMessageProgess extends AppCompatActivity implements View.OnClickListener{
    ProgressBar progressBar=null;
    Button btn_start=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_message_progess);

        progressBar=(ProgressBar)findViewById(R.id.progressBar);
        btn_start=(Button)findViewById(R.id.btn_start);
        btn_start.setOnClickListener(this);
    }

    public void onClick(View v){
        progressBar.setVisibility(View.VISIBLE);
        updateProgressBarHandler.post(updateThread);
    }

    //使用匿名内部类来复写Handler当中的handleMessage方法
    Handler updateProgressBarHandler=new Handler(){
        public void handleMessage(Message msg){
            progressBar.setProgress(msg.arg1);
            updateProgressBarHandler.post(updateThread);
        }
    };

    Runnable updateThread=new Runnable() {
        int i=0;
        @Override
        public void run() {
            System.out.println("Begin Thread");
            i=i+10;
            //获取一个消息对象
            Message message=updateProgressBarHandler.obtainMessage();
            message.arg1=i;
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            //将message加入到消息队列中
            updateProgressBarHandler.sendMessage(message);
            if (i==100){
                updateProgressBarHandler.removeCallbacks(updateThread);
            }
        }
    };
}
